package com.app.signing.view.main

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.app.DialogFragment
import android.support.v4.content.ContextCompat
import android.support.v4.view.GravityCompat
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import android.widget.LinearLayout
import android.widget.TextView
import com.app.signing.R
import com.app.signing.app.logi
import com.app.signing.data.DbManager
import com.app.signing.data.SpManager
import com.app.signing.view.login.LoginStates
import com.app.signing.view.room.Room212Activity
import com.app.signing.view.room.Room316Activity
import com.app.signing.view.room.Room320Activity
import com.app.signing.view.setting.SettingActivity
import com.app.signing.widget.LoginStatusDialog
import com.app.signing.widget.SigningSettingDialog.NoticeDialogListener
import kotlinx.android.synthetic.main.activity_main.drawer_layout
import kotlinx.android.synthetic.main.activity_main.nav_view
import kotlinx.android.synthetic.main.content_main.ll_room_212
import kotlinx.android.synthetic.main.content_main.ll_room_316
import kotlinx.android.synthetic.main.content_main.ll_room_320
import kotlinx.android.synthetic.main.layout_main.toolbar
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions

@RuntimePermissions
class MainActivity : AppCompatActivity(),
        NavigationView.OnNavigationItemSelectedListener,
        NoticeDialogListener {

    private var isShowLoginStates: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_menu_white)

        nav_view.setNavigationItemSelectedListener(this)
        setHeadView()
        initView()
    }

    override fun onResume() {
        super.onResume()
        requestPermissionWithPermissionCheck()
    }

    private fun initView() {
        ll_room_212.setOnClickListener {
            startActivity(Intent(this, Room212Activity::class.java))
        }
        ll_room_316.setOnClickListener {
            startActivity(Intent(this, Room316Activity::class.java))
        }
        ll_room_320.setOnClickListener {
            startActivity(Intent(this, Room320Activity::class.java))
        }
        val loginStates = SpManager.INSTANCE.readLoginStates()
        if (loginStates == LoginStates.loginAdmin) {
            closeRoom(ll_room_212, ll_room_316, ll_room_320)
        }
    }

    /**
     * 房间item状态关闭
     */
    private fun closeRoom(vararg views: LinearLayout) {
        for (view in views) {
            view.setBackgroundColor(ContextCompat.getColor(this, R.color.divider))
            view.isClickable = false
        }
    }

    /**
     * 侧边栏view数据显示
     */
    private fun setHeadView() {
        val userData = DbManager.INSTANCE.findUser(SpManager.INSTANCE.readLoginUserId())
        val headerLayout = nav_view.getHeaderView(0)
        val textHeadName = headerLayout.findViewById<TextView>(R.id.text_main_head_name)
        textHeadName.text = userData?.userName
        val textHeadSubName = headerLayout.findViewById<TextView>(R.id.text_main_head_sub_name)
        textHeadSubName.text = userData?.userFaculty
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> {
                drawer_layout.openDrawer(GravityCompat.START)
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_manage -> {
                startActivity(Intent(this, SettingActivity::class.java))
            }
        }
        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // NOTE: delegate the permission handling to generated function
        onRequestPermissionsResult(requestCode, grantResults)
    }

    @NeedsPermission(
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun requestPermission() {
        "权限申请成功".logi()
        val status = SpManager.INSTANCE.readLoginStates()
        if (!isShowLoginStates && status != LoginStates.loginAdmin) {
            isShowLoginStates = true
            LoginStatusDialog.newInstance().show(supportFragmentManager, "login_status")
        }
    }

    override fun onDialogPositiveClick(
        dialog: DialogFragment?,
        value: String?
    ) {
        value?.let {
            // 常用状态登录时，关闭316,320
            if (it.toInt() == LoginStates.loginSpecial) {
                closeRoom(ll_room_316, ll_room_320)
            }
        }
    }

    override fun onDialogNegativeClick(dialog: DialogFragment?) {
    }

}
